//
//  EmptyCollectionView.swift
//  pBox
//
//  Created by TianChenIMac1 on 2019/9/30.
//  Copyright © 2019 skymesh. All rights reserved.
//

import UIKit
import EmptyDataSet_Swift
import MJRefresh

public class EmptyCollectionView: UICollectionView {
    
    public var didTapEmptyView : ((UIView) -> Void)?
    public var emptyTitle : (() -> NSAttributedString?)?
    public var emptyImage : (() -> UIImage?)?
    public var emptyButtonTitle : ((UIControl.State) -> NSAttributedString?)?
    public var emptyButtonImage : ((UIControl.State) -> UIImage?)?
    public var emptyButtonBackgroundImage : ((UIControl.State) -> UIImage?)?
    public var refresh : ((EmptyCollectionView)->Void)?
    public var loadMore : ((EmptyCollectionView)->Void)?
    
    public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        setupSubViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupSubViews()
    }
    
    private func setupSubViews() {
        self.emptyDataSetSource = self
        self.emptyDataSetDelegate = self
        self.mj_header = MJRefreshNormalHeader.init(refreshingBlock: { [weak self] in
            self?.refreshAction()
        })
        self.mj_footer = MJRefreshBackNormalFooter.init(refreshingBlock: { [weak self] in
            self?.loadMoreAction()
        })
    }
    
    public func refreshAction() {
        if let _ = refresh {
            refresh?(self)
        } else {
            mj_header?.endRefreshing()
        }
    }
    
    public func loadMoreAction() {
        if let _ = loadMore {
            loadMore?(self)
        } else {
            mj_footer?.endRefreshing()
        }
    }
}

extension EmptyCollectionView : EmptyDataSetDelegate {
    public func emptyDataSet(_ scrollView: UIScrollView, didTapView view: UIView) {
        didTapEmptyView?(view)
    }
    
    public func emptyDataSet(_ scrollView: UIScrollView, didTapButton button: UIButton) {
        didTapEmptyView?(button)
    }
}

extension EmptyCollectionView : EmptyDataSetSource {
    public func title(forEmptyDataSet scrollView: UIScrollView) -> NSAttributedString? {
        return emptyTitle?() ?? NSAttributedString.init(string: "暂无记录")
    }
    
    public func image(forEmptyDataSet scrollView: UIScrollView) -> UIImage? {
        return emptyImage?()
    }
    
    public func buttonTitle(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> NSAttributedString? {
        return emptyButtonTitle?(state)
    }
    
    public func buttonImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? {
        return emptyButtonImage?(state)
    }
    
    public func buttonBackgroundImage(forEmptyDataSet scrollView: UIScrollView, for state: UIControl.State) -> UIImage? {
        return emptyButtonBackgroundImage?(state)
    }
}
